package com.financing.wap.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;

/**
 * Servlet Filter implementation class AccessFilter
 */
@Component(value="wapLoginFilter")
public class WapLoginFilter implements Filter,ApplicationContextAware{
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private IUserService userService;
	
	private static String CONTEXT_PATH = "";
	
	private static final String[] NEED_lOAD_USERINFO = {
		".*/api/uploadProduct.*",
		".*/api/biddingReceipt.*",
		".*/api/product.*",
		".*/api/recommentProduct.*",
			"^/api/fileUpload"
	};
	
    /**
     * Default constructor. 
     */
    public WapLoginFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		
		Session session = SessionUtil.getSession(true);
		UserDTO loginUser = session.getUser();
		
		Enumeration e2 = httpRequest.getAttributeNames();
		while(e2.hasMoreElements()){
			log.info(e2.nextElement());
		}
		
		log.info("phoneid :"+httpRequest.getHeader("phoneid"));
		log.info("token : "+httpRequest.getHeader("token"));
		
		log.info(httpRequest.getParameterMap());
		Enumeration el = httpRequest.getHeaderNames();
		
		while(el.hasMoreElements()){
			log.info(el.nextElement());
		}
		
		String pt = httpRequest.getParameter(Constants._PT);
		String token = null;
		Cookie[] cookies = httpRequest.getCookies();
		
		Boolean isLogin = session.getLogin();
		String _tokenHead = "";
		if(cookies != null){
			for(Cookie tokenCookie : cookies ){
				log.info("!tokenCookie name"+tokenCookie.getName());
				if(Constants._TOKEN.equals(tokenCookie.getName())){
					
					tokenCookie.setMaxAge(60*60*24*15);
					if(isLogin != null && isLogin){
						tokenCookie.setPath("/");
						httpResponse.addCookie(tokenCookie);
					}
					token = tokenCookie.getValue();
					_tokenHead = token;
					int k = 4-(token.length()%4);
					if(k!=4){
						for(int i = 0;i< k;i++){
							token = token +"=";
						}
					}
				}
			}
		}
		
		log.info("登录状态isLogin:"+isLogin);
		log.info("登录状态loginUser:"+loginUser);
		log.info("登录状态token:"+token);
		if(isLogin == null || !isLogin||loginUser == null || loginUser.getId() == null&&(!StringUtil.isNullOrEmptyStr(token))){
				try {
					
					log.info("登录状态httpRequest-token:"+httpRequest.getHeader("token"));
					
					log.info("token : "+httpRequest.getHeader("token"));
					log.info("token : "+_tokenHead);
					String tokenHead=httpRequest.getHeader("token");
					
					if(StringUtils.isBlank(tokenHead)){
						tokenHead = _tokenHead;
					}
					
					log.info("MemcacheCacheHelper.mcc.get token:"+tokenHead);
					Object o=null;
					if(StringUtils.isNotBlank(tokenHead))
						o=MemcacheCacheHelper.mcc.get(tokenHead);
					log.info("memcacheCache get token :"+o);
					//if(o!=null){
					if(token != null && SecureUtil.decrypt(token) != null) {
						token = SecureUtil.decrypt(token);
						UserDTO user = new UserDTO();
						user.setId(token);
						user = userService.getUser(user);
						if (user != null && user.getId() != null) {
							session.setLogin(true);
							session.setUser(user);
							SessionUtil.setSession(session);
						}
					}
					//}

					} catch (Exception e) {
						log.error("wap login get user info error!",e);
				}
		}
		
		String requestUri = httpRequest.getRequestURI();
		//需要登录  部分接口需要更新  用户缓存信息
		if(session.getLogin()&&needFlushUserInfo(requestUri)){
			UserDTO newUser = userService.queryUserById(session.getUser().getId());
			log.info("查询userinfo数据。。。"+newUser.toString());
			session.setUser(newUser);
		}
		
		chain.doFilter(request, response);
	}
	/**
	 * 判断当前请求是否需要更新用户信息
	 * @param requestUri
	 */
	private boolean needFlushUserInfo(String requestUri){
		
		if(StringUtils.isEmpty(requestUri) || requestUri.equals(CONTEXT_PATH)){
			return false;
		}else{
			requestUri = requestUri.replaceFirst(CONTEXT_PATH, "");
		}
		
		/**
		 *满足正则的URL
		 */
		for(int i=0; i < NEED_lOAD_USERINFO.length; i++){
			String regex = NEED_lOAD_USERINFO[i];
			if(requestUri.matches(regex)){
				return true;
			}
		}
		
		return false;
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		userService = (IUserService) applicationContext.getBean("userService");
	}
	

}